package pay.serviceImpl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import pay.common.ConstantFYJZH;
import pay.common.ConstantsOrder;
import pay.entity.OrderInfo;
import pay.entity.SysUser;
import pay.service.IOrderHelper;
import pay.utils.JsonUtils;
import pay.utils.RedisCilent;
import pay.utils.StringHelper;

@Service
public class OrderHelperImpl implements IOrderHelper {
	
	private Logger logger = LoggerFactory.getLogger(OrderHelperImpl.class);

	@Value("${producer.host}")
	private String host;

	//private RestTemplate template = new RestTemplate( new HttpComponentsClientHttpRequestFactory());

	private RestTemplate template = new RestTemplate(); 
	@Override
	public Boolean updateOrder(OrderInfo order) {

		Boolean returnVal = false;

		
		String url = "http://" + host + "/hk/RMICtr/updateOrder?sign=inner";
		
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<Object> requestEntity = new HttpEntity<Object>(order,
					headers);
			ResponseEntity<Boolean> result = template.exchange(url,
					HttpMethod.POST, requestEntity, Boolean.class, order);
			if (!result.getBody()) {
				logger.info("更新订单失败！orderId={}", order.getId());
			} else {
				returnVal = true;
			}
		} catch (Exception e) {
			logger.info("更新订单异常！");
			logger.error("更新订单异常！", e);
		}
		return returnVal;
	}

	@Override
	public List<OrderInfo> getProdNewStartOrders() {
		List<OrderInfo> orderList = null;
		String url = "http://" + host
				+ "/hk/RMICtr/getProdNewStartOrders?sign=inner";
		try {
			if (template.getForObject(url, String.class) != null) {
				String orderListStr = template.getForObject(url, String.class);

				if (pay.utils.StringHelper.isNotEmpty(orderListStr)) {
					orderList = JsonUtils.toBean(orderListStr, List.class,
							OrderInfo.class);
				}
			} else {
				logger.error("获取起标订单 返回为空");
			}
		} catch (Exception e) {
			logger.error("获取起标订单异常！", e);
			logger.info("获取起标订单异常！e={}", e);
		}
		return orderList;
	}

	public Boolean saveOrder(OrderInfo order) {
		logger.error("saveOrder will start to save order , orderId={}", order.getId());
		Boolean returnVal = false;

		String url = "http://" + host + "/hk/RMICtr/saveOrder?sign=inner";
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<Object> requestEntity = new HttpEntity<Object>(order,
					headers);

			ResponseEntity<Boolean> result = template.exchange(url,
					HttpMethod.POST, requestEntity, Boolean.class, order);
			if (!result.getBody()) {
				logger.info("保存订单失败！orderId={}", order.getId());
			} else {
				returnVal = true;
			}
		} catch (Exception e) {
			logger.error("saveOrder 保存订单异常！", e);
		}
		return returnVal;
	}

	/**
	 * 预授权失败则取消订单
	 * @param
	 * @return
	 */
    public Boolean cancelOrder(Long orderId) {
        OrderInfo order = getFromRedis(ConstantsOrder.ORDER_FYJZH_PRIX + orderId);
        Boolean returnVal = false;
        logger.info("will cancelOrderorderId={}", order.getId());
        String url = "http://" + host + "/hk/RMICtr/cancelOrder?sign=inner";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(order,
                    headers);

            ResponseEntity<Boolean> result = template.exchange(url,
                    HttpMethod.POST, requestEntity, Boolean.class, order);

            if (!result.getBody()) {
                logger.info("cancelOrder订单失败！orderId={}", order.getId());
            } else {
                returnVal = true;
                logger.info("cancelOrder success orderId={}", order.getId());
            }

        } catch (Exception e) {
            logger.info("cancelOrder异常！");
            logger.error("cancelOrder订单异常！", e);
        }
        return returnVal;
    }

    /**
     * 预授权失败则取消订单
     *
     * @param
     * @return
     */
    @Override
    public Boolean refundOrder(Long orderId) {
        Boolean result = false;

        OrderInfo order = getFromRedis(ConstantsOrder.ORDER_FYJZH_PRIX + orderId);

        if(order == null){
            logger.error("订单进行退款，订单不存在在缓存里! orderId={}", orderId);
            return  false;
        }

        logger.info("will refund Order orderId={}", order.getId());
        String url = "http://" + host + "/hk/RMICtr/refundOrder?sign=inner";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(order, headers);

            ResponseEntity<Boolean> callResult = template.exchange(url,
                    HttpMethod.POST, requestEntity, Boolean.class, order);

            if (!callResult.getBody()) {
                logger.error("refundOrder 订单失败！orderId={} callresult={}", order.getId(), callResult.getBody());
                return false;
            }

            result = true;
            logger.info("refundOrder success orderId={}", order.getId());

        } catch (Exception e) {
            logger.error("refundOrder 订单异常！", e);
        }
        return result;
    }

	@Override
	public void addIntoRedis(String keyStr, OrderInfo order) {
		RedisCilent.setString(keyStr, JsonUtils.toJson(order), 259200);

	}

	@Override
	public void updOrderInRedis(String keyStr, OrderInfo order) {
		RedisCilent.setString(keyStr, JsonUtils.toJson(order), 259200);

	}


	@Override
	public OrderInfo getFromRedis(String keyStr) {
		OrderInfo orderInfo = null;

		// 从缓存中获取预授权订单
		if (RedisCilent.existsKey(keyStr)) {
			String orderStr = RedisCilent.getString(keyStr);
			orderInfo = JsonUtils.toBean(orderStr, OrderInfo.class);
		}

		return orderInfo;
	}

	@Override
	public Boolean deleteFromRedis(String keyStr) {

		// 从缓存中获取预授权订单
		if (RedisCilent.existsKey(keyStr)) {
			RedisCilent.delKey(keyStr);
		}

		return true;

	}

	@Override
	public Boolean addToRouteInfo(OrderInfo order) {
		Boolean returnVal = false;

		String url = "http://" + host + "/hk/RMICtr/saveRouteOrder?sign=inner";
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<Object> requestEntity = new HttpEntity<Object>(order,
					headers);

			ResponseEntity<Boolean> result = template.exchange(url,
					HttpMethod.POST, requestEntity, Boolean.class, order);
			if (!result.getBody()) {
				logger.info("保存订单失败！orderId={}", order.getId());
			} else {
				returnVal = true;
			}
		} catch (Exception e) {
			logger.info("保存订单异常！");
			logger.error("保存订单异常！", e);
		}
		return returnVal;

	}

	@Override
	public Long getDJOrderAccount(Long userId) {
		SysUser user = new SysUser();
		user.setId(userId);

		Long size = Long.valueOf("0");
		/*
		String url = "http://" + host
				+ "/hk/RMICtr/getDJOrderAccount?sign=inner";
		try {

			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<Object> requestEntity = new HttpEntity<Object>(user,
					headers);

			ResponseEntity<Long> result = template.exchange(url,
					HttpMethod.POST, requestEntity, Long.class, user);

			if (result.getBody() != null) {
				size = result.getBody();
			}

		} catch (Exception e) {
			logger.error("获取冻结订单异常！", e);
			logger.info("获取冻结订单异常！e={}", e);
		}
		*/
		return size;
	}

	@Override
	public Boolean updateProductInfo(Long productId, BigDecimal amount) {
		Boolean returnVal = false;
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put("productId", productId);
			map.put("amount", String.valueOf(amount));
			System.out.println(amount.longValue());
			String url = "http://" + host
					+ "/hk/RMICtr/updateProductAmount?sign=inner";
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<Object> requestEntity = new HttpEntity<Object>(map,
					headers);	
			
			ResponseEntity<Boolean> result = template.exchange(url,
					HttpMethod.POST, requestEntity, Boolean.class, map);
			
			if (!result.getBody()) {
				logger.info("更新产品信息！productId={}", productId);
			} else {
				returnVal = true;
			}
		} catch (Exception e) {
			logger.info("更新产品信息异常！");
			logger.error("更新产品信息异常！", e);
		}
		return returnVal;
	}

	@Override
	public boolean addToRouteOrders(Long orderId, Long userId, int company) {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setId(orderId);
		orderInfo.setUserId(userId);
		orderInfo.setCompanyId(company);
		return addToRouteInfo(orderInfo);
	}

	@Override
	public void deleteFromRedis(String constantTradeType, String ssn) {
		String keyStr = constantTradeType + ssn;
		// 从缓存中获取预授权订单
		if (RedisCilent.existsKey(keyStr)) {
			RedisCilent.delKey(keyStr);
		}
	}

	@Override
	public void updateOrderStatus(Long orderId, Integer payStatus,
			Integer confirmStatus, String contract_no, String constantTradeType) {
		String orderKey = constantTradeType + orderId;
		OrderInfo order = this.getFromRedis(orderKey);
		order.setContract_no(contract_no);
		order.setPayStatus(payStatus);
		order.setConfirmStatus(confirmStatus);
		this.saveOrder(order);
	}

	@Override
	public List<String> getTranseferOrderListFromRedis() {
		
		List<String> transferOrderList = null;

		String keyStr = ConstantFYJZH.FYJZH_TRANSFER_ORDER_LIST;

		// 从缓存中获取订单信息
		if (RedisCilent.existsKey(keyStr)) {
				transferOrderList   = RedisCilent.listGet(
							ConstantFYJZH.FYJZH_TRANSFER_ORDER_LIST,  0, 20);
			logger.info("待划拨的订单总数目为 size={}", transferOrderList.size());
		}else{
			logger.info("待划拨的订单为空");
		}
		
		return transferOrderList; 
		
	}
 

	@Override
	public void delTransferOrderFromRedis(Long orderId, String  orderTransferMsg) {
		logger.info("delTransferOrderFromRedis 将要删除待划拨订单 orderId={}", orderId);
		
		RedisCilent.delListVal(ConstantFYJZH.FYJZH_TRANSFER_ORDER_LIST, 1,
				orderTransferMsg);
	}
	 

	@Override
	public List<String> getPaybackOrderListFromRedis() {
		List<String> paybackOrderList = null;

		String keyStr = ConstantFYJZH.FYJZH_PAYBACK_ORDER_LIST;

		// 从缓存中获取订单信息
		if (RedisCilent.existsKey(keyStr)) {
			paybackOrderList   = RedisCilent.listGet(
							ConstantFYJZH.FYJZH_PAYBACK_ORDER_LIST,  0, 9);	 
			logger.info("待回款划拨的订单总数目为 size={}", paybackOrderList.size());
		}else{
			logger.info("待回款划拨的订单为空");
		}
		
		return paybackOrderList;
	}

	@Override
	public void delPaybackOrderFromRedis(Long orderId, String orderPaybackMsg) {
		logger.info("delPaybackOrderFromRedis 将要删除待回款订单 orderId={}", orderId);
		
		RedisCilent.delListVal(ConstantFYJZH.FYJZH_PAYBACK_ORDER_LIST, 1,
				orderPaybackMsg);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getPayBackOrders(String productId) {
		List<Map<String, Object>> mapList = null;
		String url = "http://" + host
				+ "/hk/RMICtr/getPayBackOrders?sign=inner&productId="+productId;
		try {		
			String orderListStr = template.getForObject(url, String.class);
			if(StringHelper.isNotEmpty(orderListStr)){
				mapList = JsonUtils.toBean(orderListStr, List.class,
						Map.class);
			}else {
				logger.error("获取待回款订单 返回为空");
			}
		} catch (Exception e) {
			logger.error("获取待回款订单异常！", e);
			logger.info("获取待回款订单异常！e={}", e);
		}
		return mapList;
	}
	
}
